package com.sooth.system.dept.service;

import com.dream.boot.impl.ServiceImpl;
import com.dream.template.mapper.TemplateMapper;
import com.sooth.system.dept.view.SysDeptBo;
import com.sooth.system.dept.view.SysDeptDto;
import com.sooth.system.dept.view.SysDeptVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 部门管理 服务实现
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptVo, SysDeptBo> implements ISysDeptService {

    private final TemplateMapper templateMapper;

    @Override
    public List<SysDeptVo> selectDeptTree(SysDeptDto deptModel) {
        return templateMapper.selectTree(SysDeptVo.class, deptModel);
    }

    @Override
    public List<Long> selectDeptIdsByParentId(Long deptId) {
        List<SysDeptVo> deptVoList = super.selectList(null);
        Set<Long> deptIdSet = new HashSet<>(8);
        deptIdSet.add(deptId);
        foreachDept(deptVoList, deptIdSet);
        return new ArrayList<>(deptIdSet);
    }

    public void foreachDept(List<SysDeptVo> deptVoList, Set<Long> deptIdSet) {
        boolean add = false;
        Iterator<SysDeptVo> iterator = deptVoList.iterator();
        while (iterator.hasNext()) {
            SysDeptVo deptVo = iterator.next();
            if (deptIdSet.contains(deptVo.getParentId())) {
                deptIdSet.add(deptVo.getDeptId());
                iterator.remove();
                add = true;
            }
        }
        if (add) {
            foreachDept(deptVoList, deptIdSet);
        }
    }
}
